from flask import Flask, request, jsonify
import json
import logging
import datetime

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)

@app.route('/health', methods=['GET'])
def health_check():
    """健康检测接口"""
    try:
        return jsonify({
            'status': 'healthy',
            'message': '服务运行正常',
            'timestamp': datetime.datetime.now().isoformat()
        }), 200
    except Exception as e:
        logger.error(f"健康检测失败: {str(e)}")
        return jsonify({
            'status': 'unhealthy',
            'message': f'服务异常: {str(e)}',
            'timestamp': datetime.datetime.now().isoformat()
        }), 500

@app.route('/predict', methods=['POST'])
def predict():
    """预测接口"""
    try:
        # 获取请求数据
        if not request.is_json:
            return jsonify({
                'error': '请求格式错误',
                'message': '请发送JSON格式的数据'
            }), 400
        
        input_data = request.get_json()
        logger.info(f"收到预测请求: {input_data}")
        
        # 这里可以添加您的预测逻辑
        # 示例：简单的数据处理
        if 'data' in input_data:
            # 模拟预测处理
            result = process_prediction(input_data['data'])
            
            response = {
                'status': 'success',
                'prediction': result,
                'input_data': input_data,
                'timestamp': datetime.datetime.now().isoformat()
            }
        else:
            response = {
                'status': 'error',
                'message': '缺少必要的data字段',
                'input_data': input_data
            }
            return jsonify(response), 400
        
        return jsonify(response), 200
        
    except Exception as e:
        logger.error(f"预测接口异常: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'预测失败: {str(e)}',
            'timestamp': datetime.datetime.now().isoformat()
        }), 500

def process_prediction(data):
    """处理预测逻辑的函数"""
    # 这里实现您的具体预测逻辑
    # 示例：简单的数据处理
    if isinstance(data, list):
        return [item * 2 for item in data]
    elif isinstance(data, dict):
        return {k: v * 2 for k, v in data.items()}
    elif isinstance(data, (int, float)):
        return data * 2
    else:
        return f"处理结果: {data}"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)